package com.cc.demo.listener;


import com.cc.demo.channel.TransactionChannel;
import com.cc.demo.dto.TransactionMessage;
import com.cc.demo.entity.TransactionEventMessage;
import com.cc.demo.service.TransactionEventMessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@RequiredArgsConstructor
public class TransactionMessageListener {

    private final TransactionEventMessageService transactionEventMessageService;

    /**
     * 通过该listener来处理确认发送的message
     *
     * @param message
     */
    @StreamListener(TransactionChannel.TRANSACTION_CONFIRMED)
    public void receivedConfirmedMessage(Message<TransactionMessage<?>> message) {
        log.info("received confirmed message: {}", message.getPayload());
        Integer id = message.getPayload().getId();
        transactionEventMessageService.confirmAndSendMessage(id);
    }


    /**
     * 通过该listener来处理消费者ACK回来确认处理完成的message
     *
     * @param message
     */
    @StreamListener(TransactionChannel.TRANSACTION_COMPLETED)
    public void receivedCompletedMessage(Message<TransactionMessage<?>> message) {
        log.info("received completed message: {}", message.getPayload());
        TransactionEventMessage transactionEventMessage = transactionEventMessageService.convertMessageToTransactionEventMessage(message.getPayload());
        transactionEventMessageService.setTransactionEventMessageToCompleted(transactionEventMessage);
    }


    /**
     * 通过该listener来处理消费者ACK回来处理失败的message
     *
     * @param message
     */
    @StreamListener(TransactionChannel.TRANSACTION_FAILED)
    public void receivedErrorMessage(Message<TransactionMessage<?>> message) {
        log.info("received completed message: {}", message.getPayload());
        TransactionEventMessage transactionEventMessage = transactionEventMessageService.convertMessageToTransactionEventMessage(message.getPayload());
        transactionEventMessageService.setTransactionEventMessageToFailed(transactionEventMessage);
    }
}
